﻿using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media.Imaging;
using Labthink.PCSoft.UniversalHost4.Model.Setting;
using Labthink.PCSoft.UniversalHost4.Utility;
using Microsoft.Win32;
using SystemSettings;

namespace Labthink.PCSoft.UniversalHost4.UserControls
{
    /// <summary>
    /// UcCustomInfo.xaml 的交互逻辑
    /// </summary>
    public partial class UcCustomInfo
    {
        private NotifyManager _notify;
        private CustomInfo _info;
        private bool _isLoad;
        public UcCustomInfo()
        {
            InitializeComponent();
            BtnSave.Focus();
        }

        public string Title { get; set; } = LanguageManager.GetLanguageValue("CustomInfo");

        public string PermissionCode { get; set; } = "Per_CustomInfo";

        private void UcCustomInfo_OnLoaded(object sender, RoutedEventArgs e)
        {
            if (_isLoad) return;
            _isLoad = true;

            var w = Window.GetWindow(this);
            _notify = NotifyManager.InstanceManager(w);

            //var sd = await InstrumentManager.CurrentInstrument.Commands.GetCustomInfoAsync();

            //_info = JsonConvert.DeserializeObject<CustomInfo>(sd.Value);
            _info = CustomInfoHelper.Get();
            Common.CustomInfo = _info;
            if (_info != null)
            {
                TxtName.Value = _info.CustName;
                if (!string.IsNullOrEmpty(_info.CustLogo))
                {
                    var file = AppDomain.CurrentDomain.BaseDirectory + _info.CustLogo;
                    BinaryReader binReader = new BinaryReader(File.Open(file, FileMode.Open));
                    var fileInfo = new FileInfo(file);
                    byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
                    binReader.Close();
                    var bmp = new BitmapImage();
                    bmp.BeginInit();
                    bmp.StreamSource = new MemoryStream(bytes);
                    bmp.EndInit();
                    ImgLogo.Source = bmp;
                }
                if (!string.IsNullOrEmpty(_info.CustThumb))
                {
                    var file = AppDomain.CurrentDomain.BaseDirectory + _info.CustThumb;
                    BinaryReader binReader = new BinaryReader(File.Open(file, FileMode.Open));
                    var fileInfo = new FileInfo(file);
                    byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
                    binReader.Close();
                    var bmp = new BitmapImage();
                    bmp.BeginInit();
                    bmp.StreamSource = new MemoryStream(bytes);
                    bmp.EndInit();
                    ImgThumb.Source = bmp;
                }
            }
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            Loading.Visibility = Visibility.Visible;
            BtnSave.IsEnabled = false;
            BtnLogo.IsEnabled = false;
            BtnThumb.IsEnabled = false;
            if (_info == null)
            {
                _info = new CustomInfo();
            }
            _info.CustName = TxtName.Value;

            Common.CustomInfo = _info;
            //var sd = await InstrumentManager.CurrentInstrument.Commands.UpdateCustomInfoAsync(_info);
            var r =CustomInfoHelper.Set(_info);
            //if (r >= 0)
            //{
            //    _notify.ShowSuccess(sd.ErrorMsg);
            //}
            //else
            //{
            //    _notify.ShowError(sd.ErrorMsg);
            //}

            Loading.Visibility = Visibility.Collapsed;
            BtnSave.IsEnabled = true;
            BtnLogo.IsEnabled = true;
            BtnThumb.IsEnabled = true;
        }

        private async void BtnThumb_OnClick(object sender, RoutedEventArgs e)
        {
            var open = new OpenFileDialog
            {
                Multiselect = false,
                Filter = "Jpg|*.jpg|*.JPG|Png|*.png|*.PNG"
            };
            var result = open.ShowDialog();
            if (result != null && result.Value)
            {
                var file = open.FileName;
                BinaryReader binReader = new BinaryReader(File.Open(file, FileMode.Open));
                var fileInfo = new FileInfo(file);
                byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
                binReader.Close();

                // Init bitmap
                var img = new BitmapImage();
                img.BeginInit();
                img.StreamSource = new MemoryStream(bytes);
                img.EndInit();
                if (img.PixelWidth > 400 || img.PixelHeight > 600)
                {
                    _notify.ShowError(LanguageManager.GetLanguageValue("JpgSizeError"));
                    return;
                }

                Loading.Visibility = Visibility.Visible;
                var sd = await Common.Instrument.Commands.SendCustomThumbAsync(file);
                if (sd == "")
                {
                    _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
                    Loading.Visibility = Visibility.Collapsed;
                    return;
                }
                if (sd.StartsWith("--"))
                {
                    _notify.ShowError(sd.Replace("--", ""));
                    Loading.Visibility = Visibility.Collapsed;
                    return;
                }

                img = new BitmapImage(new Uri(file, UriKind.Absolute));
                ImgThumb.Source = img;
                if (_info == null)
                {
                    _info = new CustomInfo();
                }

                _info.CustThumb = sd;
                Loading.Visibility = Visibility.Collapsed;
            }
        }

        private async void BtnLogo_OnClick(object sender, RoutedEventArgs e)
        {
            var open = new OpenFileDialog
            {
                Multiselect = false,
                Filter = "Jpg|*.jpg|*.JPG|Png|*.png|*.PNG"
            };
            var result = open.ShowDialog();
            if (result != null && result.Value)
            {
                var file = open.FileName;
                BinaryReader binReader = new BinaryReader(File.Open(file, FileMode.Open));
                var fileInfo = new FileInfo(file);
                byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
                binReader.Close();

                // Init bitmap
                var img = new BitmapImage();
                img.BeginInit();
                img.StreamSource = new MemoryStream(bytes);
                img.EndInit();
                if (img.PixelWidth > 500 || img.PixelHeight > 200)
                {
                    _notify.ShowError(LanguageManager.GetLanguageValue("JpgSizeError"));
                    return;
                }
                Loading.Visibility = Visibility.Visible;
                var sd = await Common.Instrument.Commands.SendCustomLogoAsync(file);
                if (sd == "")
                {
                    _notify.ShowError(LanguageManager.GetLanguageValue("ActionFail"));
                    Loading.Visibility = Visibility.Collapsed;
                    return;
                }
                if (sd.StartsWith("--"))
                {
                    _notify.ShowError(sd.Replace("--", ""));
                    Loading.Visibility = Visibility.Collapsed;
                    return;
                }
                ImgLogo.Source = img;

                if (_info == null)
                {
                    _info = new CustomInfo();
                }

                _info.CustLogo = sd;
                Loading.Visibility = Visibility.Collapsed;
            }
        }
    }
}
